package cn.jw.starter.web.core.filters;

import java.io.IOException;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 缓存请求消息的filter
 *
 * @author 王广帅
 * @since 2024/4/3 20:31
 */
@WebFilter(value = "/**")
public class CacheRequestBodyFilter extends OncePerRequestFilter {
    private Logger logger = LoggerFactory.getLogger(CacheRequestBodyFilter.class);

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String contentType = request.getContentType();
        if (contentType == null) {
            return true;
        }
        if (contentType.toLowerCase(Locale.ROOT).contains("application/json")) {
            return false;
        }
        return true;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        if (!(request instanceof CacheRequestWrapper)) {
            request = new CacheRequestWrapper(request);
        }
        if (!(response instanceof ContentCachingResponseWrapper)) {
            response = new ContentCachingResponseWrapper(response);
        }
        filterChain.doFilter(request, response);
    }
}
